package com.lanou3g.code0510;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * Created by dllo on 18/5/10.
 */
/*
可以通过注解的形式
来配置servlet的名字 和路径
这种写法 就不需要去web.xml中注册了
效果和在web.xml中是一致的
 */
@WebServlet(name = "HWServlet", urlPatterns = "/error404")//注解
public class HWServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        response.getWriter().println("Hello World");

        response.setContentType("text/html;charset=UTF-8");
        ServletContext app = getServletContext();
        InputStream is = app.getResourceAsStream("Error404.html");
        String html = IOUtils.toString(is, "utf8");
        response.getWriter().println(html);

        PrintWriter writer = response.getWriter();
        Integer count = (Integer) app.getAttribute("counts");
        if (count == null) {
            count = 1;
        } else {
            count++;
        }
        app.setAttribute("counts", count);
        writer.println("访问次数:" + count);// TODO: 18/5/9 访问次数为什么从3开始?

        is.close();
        is.close();
    }
}
